import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart' hide MultipartFile, FormData;
import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:yinshui_caiying/config/config.dart';
import 'package:yinshui_caiying/http/apis.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/model/image_result_model.dart';
import 'package:yinshui_caiying/model/image_model.dart';
import 'package:yinshui_caiying/model/params_model.dart';
import 'package:yinshui_caiying/model/result_model.dart';
import 'package:yinshui_caiying/pages/project/project_list.dart';
import 'package:yinshui_caiying/services/common_services.dart';
import 'package:yinshui_caiying/services/location_services.dart';
import 'package:yinshui_caiying/services/map_services.dart';
import 'package:yinshui_caiying/utils/ImageCompressUtil.dart';
import 'package:yinshui_caiying/utils/colors.dart';
import 'package:yinshui_caiying/utils/icons.dart';
import 'package:yinshui_caiying/utils/inputformatter.dart';
import 'package:yinshui_caiying/utils/screen.dart';
import 'package:yinshui_caiying/widgets/action_text_button.dart';
import 'package:yinshui_caiying/widgets/appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:http_parser/http_parser.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:yinshui_caiying/widgets/base_scaffold.dart';
import 'package:yinshui_caiying/widgets/form/form_with_adPicker.dart';
import 'package:yinshui_caiying/widgets/my_dialog.dart';
import 'package:yinshui_caiying/widgets/form/form_with_singlePicker.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textField.dart';
import 'package:yinshui_caiying/widgets/border_dashed.dart';
import 'package:yinshui_caiying/widgets/picker/models/ad_list_result_model.dart';
import 'package:yinshui_caiying/widgets/picker/models/pickerItem_model.dart';

class ProjectCreatePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => ProjectCreatePageState();
}

class ProjectCreatePageState extends State {
  CreateProjectController vm = Get.put(CreateProjectController());
  LocationService mapService = Get.find();
  CommonService commonService = Get.find();
  // ProjectLsitPageController projectLsitPageController = Get.find();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
        appBar: BackTitleBar(
          title: '创建工程',
          action: ActionTextButton(
            title: '报警',
            width: 70.w,
            height: 34.h,
            onPressed: () {
              print('到报警页');
            },
          ),
        ),
        body: SafeArea(
            child: Form(
                key: _formKey,
                child: Container(
                    margin: EdgeInsets.only(left: 74.w, right: 75.w),
                    child: ListView(
                      children: [
                        Container(
                          height: 159.h,
                          padding: EdgeInsets.only(top: 76.w),
                          child: Text(
                            '工程创建',
                            style: TextStyle(
                                color: MyColors.main,
                                fontSize: 46.sp,
                                fontWeight: FontWeight.w500),
                          ),
                        ),
                        FormSinglePicker(
                            title: '工程类型',
                            onConfirm: vm.projectTypeCof,
                            dataList: commonService.projectTypeList,
                            value: vm._projectType),
                        FormAdPicker(
                            title: '归属地',
                            onConfirm: vm.adIdCof,
                            dataList: vm.commonService.adList,
                            name: vm.ad_name,
                            value: vm.ad_id),
                        FormInput(
                            title: '工程名称',
                            placeholder: '请输入工程名称',
                            onChanged: (value) {
                              vm._projectName.value = value;
                            },
                            request: true),
                        FormInput(
                          title: '表井编号',
                          placeholder: '请输入表井编号',
                          onChanged: (value) {
                            vm._projectCode.value = value;
                          },
                          request: true,
                        ),

                        FormInput(
                            title: '井眼深度',
                            placeholder: 'm',
                            inputFormatters: [InputFormatter.xiaoshu],
                            keyboardType: TextInputType.number,
                            unit: 'm',
                            onChanged: (value) {
                              vm._projectDeepLength.value =
                                  NumUtil.getDoubleByValueStr(value)!;
                            }),
                        // FormInput(
                        //     title: '水表通径',
                        //     placeholder: 'm',
                        //     inputFormatters: [InputFormatter.xiaoshu],
                        //     keyboardType: TextInputType.number,
                        //     unit: 'm',
                        //     onChanged: (value) {
                        //       vm._projectOutRadius.value =
                        //           NumUtil.getDoubleByValueStr(value)!;
                        //     }),
                        FormInput(
                            title: '井口内径',
                            placeholder: 'm',
                            inputFormatters: [InputFormatter.xiaoshu],
                            keyboardType: TextInputType.number,
                            unit: 'm',
                            onChanged: (value) {
                              vm._projectInRadius.value =
                                  NumUtil.getDoubleByValueStr(value)!;
                            }),
                        _listTitleWithImage('表井图片'),
                        MySeparator(),
                        _listTitleWithMap('经纬度'),
                        SizedBox(
                          height: 50.h,
                        ),
                        _saveButton(),
                        SizedBox(
                          height: 50.h,
                        ),
                        _textButton(),
                        SizedBox(
                          height: 120.h,
                        )
                      ],
                    )))));
  }

  ///跳转到工程列表
  Widget _textButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextButton(
          onPressed: () {
            // projectLsitPageController.onInit();
            // Get.delete<ProjectLsitPageController>();
            // Get.toNamed('/project_list');
            Get.back();
          },
          child: Text('工程列表'),
          style: ButtonStyle(
              foregroundColor: MaterialStateProperty.all(MyColors.main),
              textStyle: MaterialStateProperty.all(TextStyle(
                fontSize: 43.sp,
              ))),
        )
      ],
    );
  }

  ///保存按钮
  Widget _saveButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 724.w,
          height: 145.h,
          child: ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                print('提交成功');

                vm._saveForm();
              }
            },
            child: Text('保  存'),
            style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Colors.white),
                backgroundColor: MaterialStateProperty.all(MyColors.main),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(72.w)))),
                textStyle: MaterialStateProperty.all(TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w500,
                ))),
          ),
        )
      ],
    );
  }

  ///标题带照片上传及上传列表
  Widget _listTitleWithImage(String title) {
    return Container(
        child: Column(
      children: [
        Container(
          height: 147.h,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 40.sp,
                  fontWeight: FontWeight.w400,
                ),
              ),
              Container(
                width: 62.w,
                height: 62.w,
                child: IconButton(
                    padding: EdgeInsets.all(0),
                    icon: Icon(
                      Icons.camera_alt_sharp,
                      color: MyColors.main,
                      size: 62.w,
                    ),
                    onPressed: () {
                      openImagePicker();
                      // vm.getImage();
                    }),
              ),
            ],
          ),
        ),
        Obx(() => vm.imageList.length > 0 ? _imageList() : Container())
      ],
    ));
  }

  ///标题带地图控制
  Widget _listTitleWithMap(String title) {
    return Container(
      height: 147.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 40.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
          Expanded(
              flex: 1,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Obx(() => Text(
                        mapService.locationResult.value.latitude != null
                            ? mapService.locationResult.value.latitude
                                    .toString() +
                                ','
                            : "",
                        style: TextStyle(fontSize: 30.sp),
                      )),
                  Obx(() => Text(
                      mapService.locationResult.value.longitude != null
                          ? mapService.locationResult.value.longitude.toString()
                          : '',
                      style: TextStyle(fontSize: 30.sp))),
                  SizedBox(
                    width: 30.w,
                  )
                ],
              )),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Container(
                child: InkWell(
                  onTap: () {
                    //获取坐标
                    vm._getLoacation();
                  },
                  child: Text(
                    '获取',
                    style: TextStyle(
                        color: MyColors.main,
                        fontSize: 40.sp,
                        fontWeight: FontWeight.w400),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 50.w),
                child: InkWell(
                  onTap: () {
                    _openMapBox();
                    //打开地图
                  },
                  child: Text(
                    '查看',
                    style: TextStyle(
                        color: MyColors.main,
                        fontSize: 40.sp,
                        fontWeight: FontWeight.w400),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  ///打开图片选择器
  openImagePicker() {
    SmartDialog.show(
        alignmentTemp: Alignment.bottomCenter,
        widget: Container(
          height: 451.h,
          width: 100.sw,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(30.w),
                  topRight: Radius.circular(30.w))),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                height: 130.h,
                alignment: Alignment.center,
                child: Text(
                  '选择操作',
                  style:
                      TextStyle(fontSize: 56.sp, fontWeight: FontWeight.w600),
                ),
              ),
              Expanded(
                  flex: 1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        height: 120.w,
                        width: 120.w,
                        child: InkWell(
                          onTap: () {
                            vm.getImage(
                                source: ImageSource.camera,
                                callback: SmartDialog.dismiss);
                          },
                          child: Image(
                            image: AssetImage(
                                'assets/images/image_picker/camera.png'),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 287.w,
                      ),
                      Container(
                        height: 120.w,
                        width: 120.w,
                        child: InkWell(
                          onTap: () {
                            vm.getImage(
                                source: ImageSource.gallery,
                                callback: SmartDialog.dismiss);
                          },
                          child: Image(
                            image: AssetImage(
                                'assets/images/image_picker/gallery.png'),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                    ],
                  )),
              InkWell(
                onTap: () {
                  SmartDialog.dismiss();
                },
                child: Container(
                  height: 143.h,
                  width: 100.sw,
                  alignment: Alignment.center,
                  child: Text(
                    '取消',
                    style:
                        TextStyle(fontSize: 40.sp, fontWeight: FontWeight.w500),
                  ),
                  decoration: BoxDecoration(
                      border: Border(
                          top: BorderSide(
                              width: 1.w,
                              color: Color.fromRGBO(221, 221, 221, 1)))),
                ),
              )
            ],
          ),
        ));
  }

  ///图片列表
  Widget _imageList() {
    return Container(
      width: 1.sw,
      height: 165.w,
      margin: EdgeInsets.only(bottom: 55.h),
      child: Obx(() => ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: vm.imageList.length,
          itemBuilder: (BuildContext context, int index) {
            return _imageItem(index, vm.imageList);
          })),
    );
  }

  ///图片
  Widget _imageItem(int index, RxList<ImageModel> list) {
    return Container(
      height: 165.w,
      width: 165.w,
      margin: EdgeInsets.only(left: index != 0 ? 21.w : 0),
      child: Stack(
        children: [
          Align(
            alignment: Alignment.bottomLeft,
            child: InkWell(
              onTap: () {
                MyDialog.openImageView(index, list);
              },
              child: Image.network(
                list[index].path,
                width: 143.w,
                height: 143.w,
                fit: BoxFit.fill,
              ),
            ),
          ),
          Align(
              alignment: Alignment.topRight,
              child: Container(
                height: 45.w,
                width: 45.w,
                child: InkWell(
                  onTap: () {
                    MyDialog.confirmDialog(
                        title: '删除',
                        desc: '确认删除此照片吗？',
                        onConfirm: () {
                          SmartDialog.dismiss();
                          vm._deletePhoto(index, list[index]);
                        });
                  },
                  child: Image(
                    image: AssetImage('assets/images/image_picker/close.png'),
                    fit: BoxFit.fill,
                  ),
                ),
              ))
        ],
      ),
    );
  }

  ///地图
  _openMapBox() {
    SmartDialog.show(widget: MapDialog());
  }
}

///创建工程的控制器
class CreateProjectController extends GetxController {
  LocationService locationService = Get.find();
  CommonService commonService = Get.find();
  ProjectLsitPageController projectLsitPageController = Get.find();

  ///图片选择器
  final imagePicker = ImagePicker();

  ///图片列表
  final imageList = <ImageModel>[].obs;

  ///工程类型
  final _projectType = PickerItemModel().obs;

  ///工程名称
  final _projectName = "".obs;

  ///表井编号
  final _projectCode = ''.obs;

  ///井眼深度
  final _projectDeepLength = 0.0.obs;

  ///井直径
  final _projectOutRadius = 0.0.obs;

  ///井内径
  final _projectInRadius = 0.0.obs;

  ///行政区划表单id
  final ad_id = Rx<int>(0);

  ///行政区划表单name
  final ad_name = ''.obs;

  String baiduToken = '';
  @override
  void onInit() {
    _projectType(commonService.projectTypeList[0]);
    // getBaiduToken();
    super.onInit();
  }

  ///选择图片
  ///
  ///[source]来源类型ImageSource.camera 为调起摄像头，ImageSource.gallery为调起相册
  ///
  ///[callback]上传后的回调函数
  Future getImage(
      {required ImageSource source, required Function callback}) async {
    final pickedFile = await ImagePicker.pickImage(source: source);
    if (pickedFile != null) {
      ///压缩图片
      File file = await ImageCompressUtil.imageCompressAndGetFile(pickedFile);

      ///获取路径
      String path = file.path;

      ///获取名称
      String name = path.substring(path.lastIndexOf("/") + 1, path.length);

      ///获取后缀
      String suffix = name.substring(name.lastIndexOf(".") + 1, name.length);

      ///装入FormData对象类
      FormData formData = FormData.fromMap({
        'image_type': suffix,
        'file': await MultipartFile.fromFile(path,
            filename: name, contentType: MediaType.parse("image/$suffix")),
      });

      ///上传
      await uploadPhoto(formData);

      callback();
    } else {
      //未选择任何图片

      SmartDialog.showToast('未选择图片', alignment: Alignment.center);
    }
  }

  ///上传图片
  uploadPhoto(data) async {
    try {
      MyDialog.showLoading(msg: '上传中...');
      // MyDialog.showLoading(msg: '上传中...', background: Colors.black54);
      var res = await Http().post(ApiBase.FILE_UPLOAD,
          data: data,
          options: Options(
              contentType: 'multipart/form-data',
              responseType: ResponseType.plain));
      ImageResultModel result = ImageResultModel.fromJson(json.decode(res));
      if (result.code == 200) {
        imageList.add(ImageModel(
          id: result.content.data.id,
          path: result.content.data.path,
        ));
      }
      SmartDialog.dismiss();
    } catch (e) {
      print(e);
    }
  }

  ///保存新建工程
  _saveForm() async {
    if (ad_id.value == null || ad_id.value == 0) {
      SmartDialog.showToast('请选择行政区划');
      return false;
    }
    ;
    MyDialog.showLoading(msg: '新建工程');
    try {
      var res = await Http().post(ApiProject.PROJECT_ADD, data: {
        "data": {
          "name": _projectName.value,
          "longitude":
              locationService.locationResult.value.longitude.toString(),
          "latitude": locationService.locationResult.value.latitude.toString(),
          "ad_id": ad_id.value,
          "type_id": _projectType.value.value
        },
        "ac_data": {
          "ziduan1": _projectDeepLength.value,
          "ziduan2": _projectOutRadius.value,
          "ziduan3": _projectInRadius.value,
          "ziduan4": _projectCode.value
        },
        "files": {"ids": imageList.map((element) => element.id).toList()}
      });
      SmartDialog.dismiss();
      ResultModel result = ResultModel.fromJson(res);
      if (result.code == 200) {
        SmartDialog.showToast('工程新建成功');

        projectLsitPageController.keywords = _projectName.value;
        projectLsitPageController.keywordsController.text = _projectName.value;
        projectLsitPageController.resetParams();
        projectLsitPageController.getProjectListData();
        Get.back();

        ///新增成功
      } else {
        ///新增失败
      }
    } catch (e) {
      SmartDialog.dismiss();
    }
  }

  ///删除图片
  ///
  ///[index]为照片的
  _deletePhoto(index, ImageModel image) async {
    //删除图片
    List<int> ids = [image.id];
    MyDialog.showLoading(msg: '删除中...');
    var res = await Http().post(ApiBase.FILE_DELETE, data: {'ids': ids});
    SmartDialog.dismiss();
    ResultModel result = ResultModel.fromJson(res);
    if (result.code == 200) {
      imageList.removeAt(index);
      SmartDialog.showToast('删除成功');
    } else {
      SmartDialog.showToast('删除失败');
    }
  }

  ///获取位置（单次）
  _getLoacation() {
    locationService.startLocation();
  }

  projectTypeCof(PickerItemModel value) {
    _projectType(value);
  }

  adIdCof(List<AdItemModel> data) {
    ad_name.value = data.map((e) => e.name).toList().join('-');
    ad_id.value = data[data.length - 1].id;
  }
}
